//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <bsp.h>
#include <uart.h>
#include "armload.h"

EXTERN_C DECL_CODEINIT int ProgramFlash(unsigned long FlashBase,long Offset, unsigned char *Buffer, long BufferSize);

DECL_ASMLINKAGE DECL_CODEINIT void ArmLoaderStartup()
{
    uint32_t  filelen=0;
    unsigned char templen[4];
    unsigned char *pBuffer=0;
    uint32_t i=0;

    // Send query signal,ask for file length
    BspWriteComPort(COMPORT_PRINT,'?');

    // Get file length

    BspReadComPort(COMPORT_PRINT, &templen[0]);
    BspReadComPort(COMPORT_PRINT, &templen[1]);
    BspReadComPort(COMPORT_PRINT, &templen[2]);
    BspReadComPort(COMPORT_PRINT, &templen[3]);

    BspReadComPort(COMPORT_PRINT, &templen[0]);
    BspReadComPort(COMPORT_PRINT, &templen[1]);
    BspReadComPort(COMPORT_PRINT, &templen[2]);
    BspReadComPort(COMPORT_PRINT, &templen[3]);

    //BspWriteComPort(COMPORT_PRINT, filelen);
    filelen=0;
    filelen=(uint32_t)templen[0];
    filelen=filelen|((uint32_t)templen[1]<<8);
    filelen=filelen|((uint32_t)templen[2]<<16);
    filelen=filelen|((uint32_t)templen[3]<<24);
    // Send ready signal
    BspWriteComPort(COMPORT_PRINT,'<');

    // receive the file data
    pBuffer=(unsigned char*) HwBufferAddress_rom;
    for (i = filelen;i > 0;i--) {
        BspReadComPort(COMPORT_PRINT, pBuffer);
        pBuffer++;
    }

    BspWriteComPort(COMPORT_PRINT,'>');

    ProgramFlash(FLASH_BASE_rom,0,(unsigned char*)HwBufferAddress_rom, RoundUp2(filelen, 32));

    BspWriteComPort(COMPORT_PRINT,'O');
    BspWriteComPort(COMPORT_PRINT,'K');
    BspWriteComPort(COMPORT_PRINT,'1');
    return;
}
